import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getMenuList, getSystemUsers, updateRight } from '@/api/permission'
import type { MenuItem, SystemUser, UpdateRightParams } from '@/api/types/permission'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'

export const usePermissionStore = defineStore('permission', () => {
  const menuList = ref<MenuItem[]>([])
  const systemUsers = ref<SystemUser[]>([])
  const loading = ref(false)
  const selectedUserId = ref<number>()
  const selectedUsername = ref<string>()
  const userStore = useUserStore()

  // 过滤掉当前登录用户
  const filteredUsers = computed(() => {
    const currentUsername = userStore.username
    return systemUsers.value.filter(user => user.username !== currentUsername)
  })

  const fetchMenuList = async (userId?: number,isloading?:boolean) => {
    if (!selectedUsername.value) return
    if (isloading) {
      loading.value = false
    }else{
      loading.value = true
    }
    
    try {
      const response = await getMenuList({ username: selectedUsername.value })
      menuList.value = response.data.info_list
      selectedUserId.value = userId
    } catch (error) {
      console.error('获取菜单列表失败:', error)
    } finally {
      loading.value = false
    }
  }

  const fetchSystemUsers = async () => {
    try {
      const response = await getSystemUsers()
      systemUsers.value = response.data.info_list
      return response.data.info_list
    } catch (error) {
      console.error('获取账号列表失败:', error)
      return []
    }
  }

  const updateMenuRight = async (menuId: number, enabled: boolean) => {
    if (!selectedUsername.value) {
      ElMessage.warning('请先选择用户')
      return false
    }

    try {
      const params: UpdateRightParams = {
        username: selectedUsername.value,
        menuid: menuId,
        flag: enabled ? 1 : 0
      }
      
      const response = await updateRight(params)
      if (response.code === '200') {
        ElMessage.success('权限更新成功')
        return true
      } else {
        ElMessage.error('权限更新失败')
        return false
      }
    } catch (error) {
      console.error('更新权限失败:', error)
      ElMessage.error('权限更新失败')
      return false
    }
  }

  return {
    menuList,
    systemUsers,
    filteredUsers,
    loading,
    selectedUserId,
    selectedUsername,
    fetchMenuList,
    fetchSystemUsers,
    updateMenuRight
  }
}) 